<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th @click="changeSort('name')" style="cursor:pointer;">名称 <span class="badge" v-if="sortBy==='name'">{{ sortOrder }}</span></th>
          <th @click="changeSort('version')" style="cursor:pointer;">版本 <span class="badge" v-if="sortBy==='version'">{{ sortOrder }}</span></th>
          <th @click="changeSort('vendor')" style="cursor:pointer;">供应商 <span class="badge" v-if="sortBy==='vendor'">{{ sortOrder }}</span></th>
          <th @click="changeSort('packageManager')" style="cursor:pointer;">包管理器 <span class="badge" v-if="sortBy==='packageManager'">{{ sortOrder }}</span></th>
          <th @click="changeSort('createTime')" style="cursor:pointer;">创建时间 <span class="badge" v-if="sortBy==='createTime'">{{ sortOrder }}</span></th>
          <th @click="changeSort('updateTime')" style="cursor:pointer;">更新时间 <span class="badge" v-if="sortBy==='updateTime'">{{ sortOrder }}</span></th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-if="loading">
          <td colspan="8">加载中...</td>
        </tr>
        <tr v-for="p in records" :key="p.id">
          <td>{{ p.id }}</td>
          <td>{{ p.name }}</td>
          <td>{{ p.version }}</td>
          <td>{{ p.vendor }}</td>
          <td>{{ p.packageManager }}</td>
          <td>{{ p.createTime }}</td>
          <td>{{ p.updateTime }}</td>
          <td>
            <button class="btn danger" @click="$emit('delete', p.id)" :disabled="loading">删除</button>
          </td>
        </tr>
        <tr v-if="!loading && (!records || records.length === 0)">
          <td colspan="8">暂无数据</td>
        </tr>
      </tbody>
    </table>
  </div>
  
</template>

<script>
export default {
  name: 'ProductTable',
  props: {
    records: { type: Array, default: () => [] },
    loading: { type: Boolean, default: false },
    sortBy: { type: String, default: 'createTime' },
    sortOrder: { type: String, default: 'desc' },
  },
  emits: ['delete', 'change-sort'],
  setup(props, { emit }) {
    const changeSort = (field) => {
      const nextOrder = props.sortBy === field ? (props.sortOrder === 'asc' ? 'desc' : 'asc') : 'desc'
      emit('change-sort', { sortBy: field, sortOrder: nextOrder })
    }
    return { changeSort }
  }
}
</script>

